<template>
  <div class="page-score-prod-list mod-prod">
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="keyword"
            :label="$t('product.prodName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.keyword"
              type="text"
              clearable
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>
          <el-form-item
            prop="status"
            :label="$t('product.status') + ':'"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.status"
              clearable
              :placeholder="$t('product.status')"
            >
              <el-option
                :label="$t('prodList.offShelf')"
                :value="0"
              />
              <el-option
                :label="$t('prodList.onShelf')"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('product.search') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch('searchForm')"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('score:prod:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate()"
        >
          {{ $t('brand.add') }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          ref="scoreProLisTTableRef"
          :data="dataList"
          style="width: 100%"
          header-cell-class-name="table-header"
          row-class-name="table-row"
        >
          <el-table-column
            align="left"
            prop="prodName"
            :label="$t('product.prodName')"
            width="230"
          >
            <template #default="scope">
              <span class="table-cell-text">
                {{ scope.row.prodName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="pic"
            :label="$t('product.pic')"
            width="200"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <ImgShow :src="scope.row.pic" />
              </div>
            </template>
          </el-table-column>
          <!-- 市场价(元) -->
          <el-table-column
            prop="oriPrice"
            :label="$t('prodList.marketValue')"
            min-width="190"
          />
          <!-- 销售价(元) -->
          <el-table-column
            prop="price"
            :label="$t('prodList.salesPrice')"
            min-width="190"
          />
          <el-table-column
            prop="scorePrice"
            :label="$t('scoreProdList.needAccumulatePoints')"
            min-width="200"
          />
          <el-table-column
            prop="totalStocks"
            :label="$t('product.availableInventory')"
            min-width="200"
          />
          <el-table-column
            prop="status"
            :label="$t('product.status')"
            min-width="150"
          >
            <template #default="scope">
              <div v-if="scope.row.status === 1">
                {{ $t("prodList.onShelf") }}
              </div>
              <div v-else-if="scope.row.status === 0">
                {{ $t("scoreProdList.platformOffShelf") }}
              </div>
              <div v-else-if="scope.row.status === 2">
                {{ $t("prodList.violation") }}
              </div>
              <div v-else-if="scope.row.status === 3">
                {{ $t("product.pendingReview") }}
              </div>
              <div v-else-if="scope.row.status === 4">
                {{ $t("prodList.refusePass") }}
              </div>
              <div v-else>
                {{ $t("prodList.other") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="230"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('score:prod:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.prodId)"
                >
                  {{ $t("brand.revise") }}
                </div>
                <div
                  v-if="scope.row.status === 0"
                  class="default-btn text-btn"
                  @click="onChangeProdStatus(scope.row.prodId, 1)"
                >
                  {{ $t("prodList.onShelf") }}
                </div>
                <div
                  v-if="scope.row.status === 1"
                  class="default-btn text-btn"
                  @click="onChangeProdStatus(scope.row.prodId, 0)"
                >
                  {{ $t("prodList.offShelf") }}
                </div>
                <div
                  v-if="scope.row.status > 1"
                  class="default-btn text-btn"
                  @click="onApplyAuditHandle(scope.row.prodId)"
                >
                  {{ $t("prodList.offShelfManage") }}
                </div>
                <div
                  v-if="isAuth('score:prod:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.prodId)"
                >
                  {{ $t("remindPop.delete") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <!-- 下线管理弹窗-->
    <offline-event-handle
      v-if="prodOfflineHandleEventVisible"
      ref="prodOfflineHandleEventRef"
      select-url="/prod/prod/getOfflineHandleEventByProdId"
      apply-url="/prod/prod/auditApply"
      @refresh-data-list="onRefreshChange"
    />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import { ElMessageBox, ElMessage } from 'element-plus'

let tempSearchForm = null // 保存上次点击查询的请求条件
let theParams = null // 保存上次点击查询的请求条件

const dataForm = reactive({
  prodName: ''
})
const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  keyword: '',
  status: ''
})
const prodOfflineHandleEventVisible = ref(false)
let prodNameRouter = ''

onMounted(() => {
  if (useRoute().query.prodName) {
    prodNameRouter = useRoute().query.prodName
  }

  getDataList()
})
onActivated(() => {
  getDataList()
})

// 获取数据列表
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    theParams = JSON.parse(JSON.stringify(searchForm))
    tempSearchForm = {
      current: pageParam == null ? page.currentPage : pageParam.currentPage,
      keyword: prodNameRouter || dataForm.prodName,
      size: pageParam == null ? page.pageSize : pageParam.pageSize,
      prodType: 3
    }
  } else {
    tempSearchForm.current = page == null ? page.currentPage : page.currentPage
    tempSearchForm.size = page == null ? page.pageSize : page.pageSize
  }

  http({
    url: http.adornUrl('/platform/search/prod/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        tempSearchForm,
        theParams
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    for (const key in dataList.value) {
      const element = dataList.value[key]
      element.imgs = element.pic
    }
    dataForm.prodName = ''
    prodNameRouter = null
    page.total = data.total

    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.currentPage > 1) {
      page.currentPage = 1
      getDataList()
    }
  })
}
const Router = useRouter()
// 新增 / 修改
const onAddOrUpdate = (id) => {
  Router.push({
    path: '/member/score/prod/info',
    query: { prodId: id }
  })
}
// 删除
const onDelete = (id) => {
  ElMessageBox.confirm($t('scoreProdList.isDelete'), $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/platform/scoreProduct/${id}`),
        method: 'delete',
        data: http.adornData({})
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            getDataList(page)
          }
        })
      })
    })
    .catch(() => { })
}
const onChangeProdStatus = (id, status) => {
  ElMessageBox.confirm($t('remindPop.makeSure') + ' ' + `[${status ? $t('prodList.onShelf') : $t('prodList.offShelf')}]` + ' ' + $t('remindPop.operation') + '?', $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl('/platform/scoreProduct/prodStatus'),
        method: 'put',
        data: http.adornData({
          status,
          prodId: id
        })
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            getDataList(page)
          }
        })
      })
    })
}
// 条件查询
const onSearch = (newData = false) => {
  getDataList(page, newData)
}
// 申请审核
const prodOfflineHandleEventRef = ref(null)
const onApplyAuditHandle = (id) => {
  prodOfflineHandleEventVisible.value = true
  nextTick(() => {
    prodOfflineHandleEventRef.value?.init(id)
  })
}
// 回调刷新
const onRefreshChange = () => {
  getDataList()
}
/**
 * 重置表单
 * @param {String} formName 表单名称
 */
const searchFormRef = ref(null)
const onResetSearch = () => {
  searchFormRef.value.resetFields()
}
const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}

</script>

<style lang="scss" scoped>

</style>
